<template>
  <div class="address-page">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h2 class="text-lg font-medium">收货地址管理</h2>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span>新增收货地址</span>
          </el-button>
        </div>
      </template>

      <!-- 地址列表 -->
      <div class="address-list">
        <el-empty v-if="addressList.length === 0" description="暂无收货地址">
          <el-button type="primary" @click="handleAdd">添加收货地址</el-button>
        </el-empty>

        <div v-else class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div
            v-for="address in sortedAddressList"
            :key="address.id"
            class="address-item border rounded-lg p-4 relative hover:shadow-md transition-shadow"
            :class="{ 'border-primary': address.isDefault }"
          >
            <!-- 默认地址标签 -->
            <div
              v-if="address.isDefault"
              class="absolute top-0 right-0 bg-primary text-white px-2 py-1 text-xs rounded-bl-lg rounded-tr-lg"
            >
              默认地址
            </div>

            <!-- 地址标签 -->
            <div class="address-tags mb-3 flex items-center gap-2">
              <el-tag
                v-if="address.tag"
                :type="getTagType(address.tag)"
                size="small"
              >
                {{ address.tag }}
              </el-tag>
            </div>

            <!-- 地址信息 -->
            <div class="mb-4">
              <div class="flex items-center mb-2">
                <span class="font-medium">{{ address.name }}</span>
                <span class="text-gray-500 mx-4">{{
                  formatPhone(address.phone)
                }}</span>
              </div>
              <div class="text-gray-600 break-all">
                {{ formatAddress(address) }}
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex justify-between items-center">
              <div class="flex items-center">
                <el-switch
                  v-model="address.isDefault"
                  active-text="设为默认"
                  :disabled="address.isDefault"
                  @change="handleSetDefault(address)"
                />
              </div>
              <div class="space-x-2">
                <el-button type="primary" text @click="handleEdit(address)">
                  <el-icon><Edit /></el-icon>
                  <span>编辑</span>
                </el-button>
                <el-button
                  type="danger"
                  text
                  @click="handleDelete(address)"
                  :disabled="address.isDefault"
                >
                  <el-icon><Delete /></el-icon>
                  <span>删除</span>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog
      v-model="showAddressDialog"
      :title="editingAddress ? '编辑收货地址' : '新增收货地址'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="收货人" prop="name">
          <el-input
            v-model="addressForm.name"
            placeholder="请输入收货人姓名"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="addressForm.phone"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            :props="{
              expandTrigger: 'hover',
              checkStrictly: false,
            }"
            placeholder="请选择所在地区"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址，如街道、门牌号等"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="地址标签">
          <div class="flex items-center gap-2">
            <el-radio-group v-model="addressForm.tag">
              <el-radio-button label="家">家</el-radio-button>
              <el-radio-button label="公司">公司</el-radio-button>
              <el-radio-button label="学校">学校</el-radio-button>
            </el-radio-group>
            <el-input
              v-if="addressForm.tag === '自定义'"
              v-model="addressForm.customTag"
              placeholder="请输入自定义标签"
              class="w-24"
            />
            <el-button link type="primary" @click="addressForm.tag = '自定义'">
              自定义
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault"
            >设为默认收货地址</el-checkbox
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveAddress">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";

// 地址列表数据
const addressList = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138000",
    province: "广西壮族自治区",
    city: "贵港市",
    district: "港北区",
    detail: "江北大道123号",
    isDefault: true,
    tag: "家",
  },
  {
    id: 2,
    name: "李四",
    phone: "13900139000",
    province: "广西壮族自治区",
    city: "贵港市",
    district: "港南区",
    detail: "港南大道456号",
    isDefault: false,
    tag: "公司",
  },
]);

// 按默认地址排序的地址列表
const sortedAddressList = computed(() => {
  return [...addressList.value].sort((a, b) => {
    if (a.isDefault === b.isDefault) return 0;
    return a.isDefault ? -1 : 1;
  });
});

// 地址表单
const addressForm = ref({
  name: "",
  phone: "",
  region: [],
  detail: "",
  isDefault: false,
  tag: "家",
  customTag: "",
});

// 表单校验规则
const addressRules = {
  name: [
    { required: true, message: "请输入收货人姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  region: [{ required: true, message: "请选择所在地区", trigger: "change" }],
  detail: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
    { min: 5, max: 100, message: "长度在 5 到 100 个字符", trigger: "blur" },
  ],
};

// 地区选项（示例数据）
const regionOptions = [
  {
    value: "广西",
    label: "广西壮族自治区",
    children: [
      {
        value: "贵港",
        label: "贵港市",
        children: [
          { value: "港北", label: "港北区" },
          { value: "港南", label: "港南区" },
          { value: "覃塘", label: "覃塘区" },
          { value: "平南", label: "平南县" },
          { value: "桂平", label: "桂平市" },
        ],
      },
    ],
  },
];

// 控制弹窗显示
const showAddressDialog = ref(false);
const editingAddress = ref(null);
const addressFormRef = ref(null);

// 新增地址
const handleAdd = () => {
  editingAddress.value = null;
  addressForm.value = {
    name: "",
    phone: "",
    region: [],
    detail: "",
    isDefault: false,
    tag: "家",
    customTag: "",
  };
  showAddressDialog.value = true;
};

// 编辑地址
const handleEdit = (address) => {
  editingAddress.value = address;
  addressForm.value = {
    name: address.name,
    phone: address.phone,
    region: [address.province, address.city, address.district],
    detail: address.detail,
    isDefault: address.isDefault,
    tag: address.tag || "家",
    customTag:
      address.tag && !["家", "公司", "学校"].includes(address.tag)
        ? address.tag
        : "",
  };
  showAddressDialog.value = true;
};

// 删除地址
const handleDelete = async (address) => {
  if (address.isDefault) {
    ElMessage.warning("默认地址不能删除");
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除该收货地址吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用删除地址API
    addressList.value = addressList.value.filter(
      (item) => item.id !== address.id,
    );
    ElMessage.success("地址已删除");
  } catch {
    // 用户取消操作
  }
};

// 设置默认地址
const handleSetDefault = async (address) => {
  if (address.isDefault) return;

  try {
    // TODO: 调用设置默认地址API
    addressList.value.forEach((item) => {
      item.isDefault = item.id === address.id;
    });
    ElMessage.success("默认地址已更新");
  } catch (error) {
    ElMessage.error("设置默认地址失败");
  }
};

// 获取标签类型
const getTagType = (tag) => {
  const typeMap = {
    家: "success",
    公司: "primary",
    学校: "warning",
  };
  return typeMap[tag] || "info";
};

// 格式化手机号
const formatPhone = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

// 格式化完整地址
const formatAddress = (address) => {
  return `${address.province}${address.city}${address.district}${address.detail}`;
};

// 保存地址
const handleSaveAddress = () => {
  addressFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const formData = addressForm.value;
        const addressData = {
          name: formData.name,
          phone: formData.phone,
          province: formData.region[0],
          city: formData.region[1],
          district: formData.region[2],
          detail: formData.detail,
          isDefault: formData.isDefault,
          tag: formData.tag === "自定义" ? formData.customTag : formData.tag,
        };

        if (editingAddress.value) {
          // 更新现有地址
          const index = addressList.value.findIndex(
            (item) => item.id === editingAddress.value.id,
          );
          if (index !== -1) {
            // TODO: 调用更新地址API
            addressList.value[index] = {
              ...editingAddress.value,
              ...addressData,
            };
          }
        } else {
          // 添加新地址
          // TODO: 调用新增地址API
          const newAddress = {
            id: Date.now(),
            ...addressData,
          };

          if (newAddress.isDefault) {
            addressList.value.forEach((item) => {
              item.isDefault = false;
            });
          }

          addressList.value.push(newAddress);
        }

        showAddressDialog.value = false;
        ElMessage.success(editingAddress.value ? "地址已更新" : "地址已添加");
        editingAddress.value = null;
      } catch (error) {
        ElMessage.error("保存失败，请重试");
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.address-page {
  .address-item {
    @apply relative transition-all duration-300;

    &:hover {
      @apply shadow-lg transform -translate-y-1;

      .address-actions {
        @apply opacity-100;
      }
    }
  }

  :deep(.el-dialog) {
    .el-radio-button__inner {
      @apply px-3 py-1;
    }
  }
}
</style>
